import { Request, Response } from 'express';
import { PrismaClient } from '@prisma/client';
import { ResponseHelper } from '../utils/response';

const prisma = new PrismaClient();

/**
 * 评分请求体接口
 */
interface RatingBody {
  score: number;
}

/**
 * 为地点评分（创建或更新）
 * POST /api/v1/locations/:id/ratings
 * 需要JWT认证
 */
export const rateLocation = async (req: Request, res: Response): Promise<void> => {
  try {
    if (!req.user) {
      ResponseHelper.unauthorized(res, '请先登录');
      return;
    }

    const { id } = req.params;
    const locationId = parseInt(id, 10);

    if (isNaN(locationId)) {
      ResponseHelper.validationError(res, [
        { field: 'id', message: '无效的地点ID' }
      ]);
      return;
    }

    const { score } = req.body as RatingBody;

    // 验证评分
    if (score === undefined || score === null) {
      ResponseHelper.validationError(res, [
        { field: 'score', message: '评分不能为空' }
      ]);
      return;
    }

    if (typeof score !== 'number' || score < 0 || score > 5) {
      ResponseHelper.validationError(res, [
        { field: 'score', message: '评分必须是0-5之间的数字' }
      ]);
      return;
    }

    // 检查地点是否存在且已审核通过
    const location = await prisma.location.findUnique({
      where: { id: locationId }
    });

    if (!location) {
      ResponseHelper.notFound(res, '地点不存在');
      return;
    }

    if (location.status !== 'APPROVED') {
      ResponseHelper.error(res, '该地点暂未通过审核，无法评分', 400);
      return;
    }

    // 使用upsert创建或更新评分
    const rating = await prisma.rating.upsert({
      where: {
        userId_locationId: {
          userId: req.user.id,
          locationId
        }
      },
      update: {
        score
      },
      create: {
        userId: req.user.id,
        locationId,
        score
      },
      include: {
        user: {
          select: {
            id: true,
            nickname: true,
            avatarUrl: true
          }
        }
      }
    });

    // 计算新的平均评分
    const allRatings = await prisma.rating.findMany({
      where: { locationId },
      select: { score: true }
    });

    const totalScore = allRatings.reduce((sum, r) => sum + r.score, 0);
    const avgRating = allRatings.length > 0 ? totalScore / allRatings.length : 0;

    ResponseHelper.success(res, {
      rating,
      avgRating: parseFloat(avgRating.toFixed(1)),
      ratingsCount: allRatings.length
    }, '评分成功', 201);

  } catch (error: any) {
    console.error('评分失败:', error);
    ResponseHelper.serverError(res, '评分失败', error);
  }
};

/**
 * 获取用户对某地点的评分
 * GET /api/v1/locations/:id/ratings/my
 * 需要JWT认证
 */
export const getMyRating = async (req: Request, res: Response): Promise<void> => {
  try {
    if (!req.user) {
      ResponseHelper.unauthorized(res, '请先登录');
      return;
    }

    const { id } = req.params;
    const locationId = parseInt(id, 10);

    if (isNaN(locationId)) {
      ResponseHelper.validationError(res, [
        { field: 'id', message: '无效的地点ID' }
      ]);
      return;
    }

    const rating = await prisma.rating.findUnique({
      where: {
        userId_locationId: {
          userId: req.user.id,
          locationId
        }
      },
      include: {
        user: {
          select: {
            id: true,
            nickname: true,
            avatarUrl: true
          }
        }
      }
    });

    if (!rating) {
      ResponseHelper.success(res, null, '尚未评分');
      return;
    }

    ResponseHelper.success(res, rating, '获取成功');

  } catch (error: any) {
    console.error('获取评分失败:', error);
    ResponseHelper.serverError(res, '获取评分失败', error);
  }
};

/**
 * 删除评分
 * DELETE /api/v1/locations/:id/ratings
 * 需要JWT认证
 */
export const deleteRating = async (req: Request, res: Response): Promise<void> => {
  try {
    if (!req.user) {
      ResponseHelper.unauthorized(res, '请先登录');
      return;
    }

    const { id } = req.params;
    const locationId = parseInt(id, 10);

    if (isNaN(locationId)) {
      ResponseHelper.validationError(res, [
        { field: 'id', message: '无效的地点ID' }
      ]);
      return;
    }

    // 检查评分是否存在
    const existingRating = await prisma.rating.findUnique({
      where: {
        userId_locationId: {
          userId: req.user.id,
          locationId
        }
      }
    });

    if (!existingRating) {
      ResponseHelper.notFound(res, '评分不存在');
      return;
    }

    // 删除评分
    await prisma.rating.delete({
      where: {
        userId_locationId: {
          userId: req.user.id,
          locationId
        }
      }
    });

    ResponseHelper.success(res, null, '删除成功');

  } catch (error: any) {
    console.error('删除评分失败:', error);
    ResponseHelper.serverError(res, '删除评分失败', error);
  }
};
